<template>
    <div id='container'></div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { Chart } from '@antv/g2'
const labelFormatter = (d) => Math.abs(d) + (d < 0 ? 'BC' : d > 0 ? 'AC' : '') 
let chart
const left = (d) => d.end > -1500 && d.start > -3000
onMounted(() => {
    chart = new Chart({
        container,
        autoFit: true,
    });
    chart
        .coordinate({
            transform: [
                {
                    type: 'transpose'
                }
            ]
        })
        .title('多轴条形图')
        .interval()
        .data({
            type: 'fetch',
            value: '/g2Api/world-history.json',
            // transform: [
            //     {
            //         type: 'log'
            //     }
            // ]
        })
        .transform({type: 'sortX', by: 'y'})
        .transform({type: 'sortColor', by: 'y', reducer: 'min'})
        .axis('y', [
            {
                labelFormatter,
                tickCount: 5,
                grid: null,
                title: null
            },
            {
                position: 'top',
                labelFormatter,
                title: null
            }
        ])
        .axis('x', false)
        .encode('x', 'civilization')
        .encode('y', ['start', 'end'])
        .encode('color', 'region')
        .scale('color', { palette: 'set2' })
        .label({
            text: 'civilization',
            position: (d) => (left(d) ? 'left' : 'right'),
            textAlign: (d) => (left(d) ? 'end' : 'start'),
            dx: (d) => (left(d) ? -5 : 5),
            fontSize: 10
        })
        .tooltip([
            {
                name: 'start', 
                field: 'start',
                valueFormatter: labelFormatter
            },
            {
                name: 'end', 
                field: 'end',
                valueFormatter: labelFormatter
            }
        ])

    chart.render();
});

// 销毁
onUnmounted(() => {
    chart.destroy();
    chart = null;
});
</script>

<style lang='less' scoped>
#container {
    width: 800px;
    height: 600px;
}
</style>